//
//  HCMainViewController.m
//  water
//
//  Created by chck999 on 2021/8/24.
//

#import "HCMainViewController.h"
#import "Water.h"
#import <Masonry/Masonry.h>
#import "NSString+labelSize.h"
#import <sqlite3.h>
#import "FMDatabase.h"
#import <UserNotifications/UserNotifications.h>
#import <AFNetworking.h>
#import <MQTTClient/MQTTClient.h>
#import <MQTTClient/MQTTSessionManager.h>


#define mDevice  ([[[UIDevice currentDevice] systemVersion] floatValue])

@interface HCMainViewController ()<MQTTSessionManagerDelegate>

// 完成时的控件
@property (nonatomic,weak)UIView * doneView;
// 每次饮水量
@property (nonatomic,assign) int waterIntake;
//总
@property (nonatomic,assign) float total;
// 记录喝水次数
@property (nonatomic,assign) int index ;
@property (nonatomic, strong) Water *waterView;
//顶部 提醒
@property (nonatomic, weak) UILabel *tips;
// 马上开始 按钮
@property (nonatomic, weak) UIButton *startBtn;
// 底部 提示(开启推送,将.....)
@property (nonatomic, weak) UILabel *bottomTip;
// 进度label
@property (nonatomic, weak) UILabel *processLabel;
// 杯子图标
@property (nonatomic, weak) UIImageView *cupImageView;
// 数据库
@property (nonatomic, strong) FMDatabase *database;
// 打开数据库是否成功
@property (nonatomic, assign) BOOL success;

@property (nonatomic, assign) NSInteger setButtonState;
@property (nonatomic, copy)   NSString *progress;
@property (nonatomic, copy)   NSString *lastTime;
@property (nonatomic, copy)   NSString *weightStr;

@property (nonatomic,strong) MQTTSessionManager *manager;
@property (nonatomic,strong) NSString *rootTopic;

@end

@implementation HCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 1;
    
    self.view.backgroundColor = [UIColor colorWithRed:36/255.0 green:46/255.0 blue:52/255.0 alpha:1.0];
    
    // 创建/读取本地数据库
    NSString *path            = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"datafmdb.sqlite"];
    FMDatabase *database      = [FMDatabase databaseWithPath:path];
    self.database             = database;
    BOOL success              =  [database open];
    self.success              =success;
    if (success) {
        NSLog(@"打开数据库成功!");
        [self selectWithState:success];
                
    }else{
        NSLog(@"创建数据库失败!");
    }
    
    // 背景动态水
    self.waterView = [[Water alloc] initWithFrame:(self.view.bounds)];
    [self.view addSubview:self.waterView];
    
    // 顶部 提醒
    UILabel * tips = [[UILabel alloc] init];
    self.tips      = tips;
    tips.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tips];
    
    
    if (mDevice < 8.0) {
        tips.font      = [UIFont systemFontOfSize:32];
    } else {
        tips.font      = [UIFont fontWithName:@"PingFangSC-Ultralight" size:36];
    }
    tips.text      = @"提醒";
    tips.textColor = [UIColor whiteColor];
    
    // 判断是否隐藏
    if (self.setButtonState == 0) {
        tips.hidden = NO;
    }else tips.hidden = YES;
    
    [tips mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(72, 50));
        make.top.equalTo(self.view).offset(55);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    // 底部label
    UILabel * bottomTip   = [[UILabel alloc] init];
    self.bottomTip        = bottomTip;
    bottomTip.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:bottomTip];
    
    if (mDevice < 8.0) {
        bottomTip.font        =  [UIFont systemFontOfSize:28];
    } else {
        bottomTip.font        =  [UIFont fontWithName:@"PingFangSC-Regular" size:28];
    }
    
    // 马上开始按钮
    UIButton * startBtn      = [[UIButton alloc] init];
    self.startBtn            = startBtn;
    [self.view addSubview:startBtn];
    
    if (mDevice < 8.0) {
            startBtn.titleLabel.font = [UIFont systemFontOfSize:28];
    } else {
        startBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:36];
    }

    if (self.setButtonState == 0) {
        bottomTip.text      = @"开启推送,将按计划提醒你喝水";
    }else {
        bottomTip.text      = [NSString stringWithFormat:@"上一次喝水的时间是:%@",self.lastTime];

    }
    
    bottomTip.textColor = [UIColor whiteColor];
    
    if (mDevice < 8.0) {
        bottomTip.font      = [UIFont systemFontOfSize:13];
    } else {
        bottomTip.font      = [UIFont fontWithName:@"PingFangSC-Light" size:14];
    }
    
    
    CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    CGSize realSize = [bottomTip.text textSizewithFont:[UIFont systemFontOfSize:14] andMaxSize:maxSize];
    
    [bottomTip mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.bottom.equalTo(self.view).offset(-27);
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(realSize);
        
    }];

    [startBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [startBtn setBackgroundColor:[UIColor whiteColor]];
    
    if (mDevice < 8.0) {
        startBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    } else {
        startBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:18];
    }
    
    
    [startBtn.layer setMasksToBounds:YES];
    [startBtn.layer setCornerRadius:25];
    
    if (self.setButtonState == 0) {
        [startBtn setTitle:@"马上开始" forState:UIControlStateNormal];
    } else {
        [startBtn setTitle:@"喝水" forState:UIControlStateNormal];
        // 如果是第三种状态,则禁止按钮的点击
        startBtn.enabled  = self.setButtonState == 2 ? NO : YES;

    }
    
    [startBtn addTarget:self action:@selector(didClickStartButton:) forControlEvents:UIControlEventTouchUpInside];

    [startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.bottom.equalTo(bottomTip.mas_top).offset(-9);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(175.5, 49));
    }];
    
    // 进度label
    UILabel * processLabel   = [[UILabel alloc] init];
    self.processLabel        = processLabel;
    [self.view addSubview:processLabel];
    
    int total = 0;
    NSString * sql           = @"SELECT waterIntakeStr  FROM t_firstSeting ;";
    FMResultSet *result      = [self.database executeQuery:sql];
    while ([result next]) {
        
        self.waterIntake     = [result stringForColumnIndex:0].intValue;
        total                = self.weightStr.intValue * 40 ;
        self.total           = total;
    }
    
    processLabel.text        = [NSString stringWithFormat:@"%@/%dML",self.progress,total];
    processLabel.font        =  [UIFont fontWithName:@"PingFangSC-Light" size:17];
    processLabel.textColor   = [UIColor whiteColor];
    processLabel.textAlignment = NSTextAlignmentRight;
    if (self.setButtonState == 0) {
        processLabel.hidden = YES;
    } else {
        processLabel.hidden = NO;
    }

    [processLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(120.5, 24));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuide).offset(15);
    }];
    
    // 杯子图标
    UIImageView * cupImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"drink 1"]];
    self.cupImageView          = cupImageView;
    [self.view addSubview:cupImageView];
    
    if (self.setButtonState == 0) {
        cupImageView.hidden = YES;
    } else {
        cupImageView.hidden = NO;
    }
    
    [cupImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(processLabel);
        make.left.equalTo(processLabel.mas_right);
    }];
//完成时间
    UIView * doneView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 180, 28+14.5+54)];
    doneView.backgroundColor = [UIColor blackColor];
    UIImageView * doneCup = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Group 3"]];
    UILabel * doneLabel   = [[UILabel alloc] init];
    doneLabel.text        = @"今天的计划已完成";
    
    if (mDevice < 8.0) {
        doneLabel.font        = [UIFont systemFontOfSize:12];
    } else {
        doneLabel.font        = [UIFont fontWithName:@"PingFangSC-Light" size:20];
    }
    
    
    doneLabel.textColor   = [UIColor whiteColor];
    [doneView addSubview:doneLabel];
        [doneView addSubview:doneCup];
    
    [self.view addSubview:doneView];
    self.doneView         = doneView;
    
    
    [doneCup mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(doneView);
        make.centerX.equalTo(doneLabel);
    }];
    
    [doneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(doneView);
        make.top.equalTo(doneCup.mas_bottom).offset(14.5);
        make.height.equalTo(@28);
    }];
    


    [doneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-100);
        make.centerX.equalTo(self.view);
    }];
    
    
    self.doneView.hidden = (self.setButtonState == 2 ? NO : YES);
    float initHeight = mDevice < 8.0 ? 120 : 200;
    
    self.waterView.height = (self.progress.floatValue / self.total) * ([UIScreen mainScreen].bounds.size.height - initHeight)  + initHeight;
    
    NSDate * today = [NSDate date];
    NSDateFormatter * forma = [[NSDateFormatter alloc] init];
    forma.dateFormat = @"MM:dd";
    NSString * todayStr = [forma stringFromDate:today];
    
    // 在数据库中取出最后一条记录的时间,如果比今天早一天,则刷新界面
    
    NSString * time1 ;
    
    NSString * sql1 = @"SELECT time FROM t_record";
    FMResultSet *result1 = [self.database executeQuery:sql1];
    
    while ([result1 next]) {
        time1 = [result1 stringForColumnIndex:0];
    }
    
    NSString * time2 = todayStr;
    
    
    NSDateFormatter * form = [[NSDateFormatter alloc] init];
    form.dateFormat = @"MM:dd";
    
    
    NSDate * date1 = [form dateFromString:time1];
    NSDate * date2 = [form dateFromString:time2];
    
    
    BOOL isEquel =  [date1 isEqualToDate:date2];
    
    if (!isEquel) {
        // 如果不相同,说明是新的一天
        
        self.progress = @"0";
        self.waterView.height = (self.progress.floatValue / self.total) * ([UIScreen mainScreen].bounds.size.height - initHeight)  + initHeight;
        self.processLabel.text        = [NSString stringWithFormat:@"%@/%dML",self.progress,total];
        
        self.startBtn.enabled = YES;
        self.doneView.hidden  = YES;
        
        self.setButtonState   = 1;
        NSString * sql2 = [NSString  stringWithFormat:@"UPDATE t_mainSeting SET setButtonState=1"];
        BOOL update = [self.database executeUpdate:sql2];
        if (update) {
            NSLog(@"更新成功");
        }
    }
    [self sendData];
}
-(void)sendData{
    NSString *deviceID = [UIDevice currentDevice].identifierForVendor.UUIDString;
    NSString *appId = @"olc2g0";
    NSString *clientId = [NSString stringWithFormat:@"%@@%@",deviceID,appId];
    self.rootTopic = @"test";
    NSString *password = @"123456";
    BOOL  isSSL = FALSE;
    if(!self.manager){
        self.manager = [[MQTTSessionManager alloc] init];
        self.manager.delegate = self;
        self.manager.subscriptions = @{[NSString stringWithFormat:@"%@/IOS", self.rootTopic]:@(0)};
        [self getTokenWithUsername:self.username password:password completion:^(NSString *token) {
            [self bindWithUserName:self.username password:token cliendId:clientId isSSL:isSSL];
        }];
    }else{
        [self.manager connectToLast:nil];
    }
}
- (void)connect {
    [self.manager connectToLast:nil];
}

- (void)disConnect {
    [self.manager disconnectWithDisconnectHandler:nil];
    self.manager.subscriptions = @{};
    
}

- (void)getTokenWithUsername:(NSString *)username password:(NSString *)password completion:(void (^)(NSString *token))response {
    NSString *urlString = @"https://a1.easemob.com/1107210408041180/drinkwater/token";
    //初始化一个AFHTTPSessionManager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置请求体数据为json类型
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //设置响应体数据为json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *parameters = @{@"grant_type":@"password",
                                 @"username":username,
                                 @"password":password
                                 };
   
    __block NSString *token  = @"";
    [manager POST:urlString
             parameters:parameters
             headers:nil
             progress:nil
             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSError *error = nil;
                        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&error];
                        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                        NSLog(@"%s jsonDic:%@",__func__,jsonDic);
                        token = jsonDic[@"access_token"];
                        response(token);}
             failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"%s error:%@",__func__,error.debugDescription);
                        response(token);
    }];
}

- (void)bindWithUserName:(NSString *)username password:(NSString *)password cliendId:(NSString *)cliendId isSSL:(BOOL)isSSL{
    [self.manager connectTo:@"olc2g0.cn1.mqtt.chat"
                                port:1883
                                 tls:isSSL
                           keepalive:60
                               clean:YES
                                auth:YES
                                user:username
                                pass:password
                                will:NO
                           willTopic:nil
                             willMsg:nil
                             willQos:0
                      willRetainFlag:NO
                        withClientId:cliendId
                      securityPolicy:[self customSecurityPolicy]
                        certificates:nil
                       protocolLevel:4
                      connectHandler:nil];
    
}

- (MQTTSSLSecurityPolicy *)customSecurityPolicy
{
    MQTTSSLSecurityPolicy *securityPolicy = [MQTTSSLSecurityPolicy policyWithPinningMode:MQTTSSLPinningModeNone];
    
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesCertificateChain = YES;
    securityPolicy.validatesDomainName = NO;
    return securityPolicy;
}

// 获取服务器返回数据
- (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained {
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString *currentUsername = dict[@"username"];
    if([currentUsername isEqualToString:self.username]){
#pragma mark 添加通知
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
            UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert;
            [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    NSLog(@"注册成功");
                }else{
                    NSLog(@"注册失败");
                }
            }];
        }
        
        NSString * sqlForTime = @"SELECT getupStr FROM t_firstSeting";
        FMResultSet * resultForTime = [self.database executeQuery:sqlForTime];
        
        NSString * getup =@"";
        while ([resultForTime next]) {
            getup = [resultForTime stringForColumnIndex:0];
        }
        
        NSArray * moning = [getup componentsSeparatedByString:@":"];
        int moningHour = [moning[0] intValue];

        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = @"记得每天喝水哦";

        NSDateComponents *components = [[NSDateComponents alloc] init];
        components.hour = moningHour;
        components.minute = 0;
        components.hour = 1;//小时
        UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];

        //第四步：创建UNNotificationRequest通知请求对象
        NSString *requertIdentifier = @"RequestIdentifier";
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requertIdentifier content:content trigger:calendarTrigger];

        //第五步：将通知加到通知中心
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        }];
        
        [[UIApplication sharedApplication]registerForRemoteNotifications];
    }
    
}

- (void)dealloc
{
    [self disConnect];
}


#pragma mark 点击马上开始/喝水
- (void)didClickStartButton:(UIButton *)btn {

    if ([btn.currentTitle isEqualToString:@"马上开始"]) {
        NSString * sql = @"UPDATE t_mainSeting SET setButtonState = 1;";
        
        BOOL success         =  [self.database executeUpdate:sql];
        if (success) {}
        self.setButtonState         = 1;
        self.tips.hidden            = YES;
        self.processLabel.hidden    =NO;
        self.cupImageView.hidden    = NO;

        [self.startBtn setTitle:@"喝水" forState:UIControlStateNormal];
        self.bottomTip.text         = [NSString stringWithFormat:@"上一次喝水的时间是:%@",self.lastTime];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[self.username] forKeys:@[@"username"]];
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        [self.manager sendData:data
                         topic:[NSString stringWithFormat:@"%@/%@",
                                self.rootTopic,
                                @"IOS"]//此处设置多级子topic
                           qos:0
                        retain:FALSE];
    }else {
    
        NSLog(@"喝水");
        
        self.progress = [NSString stringWithFormat:@"%d",self.waterIntake + self.progress.intValue ];
        self.waterView.height = (float)(self.progress.floatValue / self.total) * ([UIScreen mainScreen].bounds.size.height - 200)  + 200;
        
        self.processLabel.text = [NSString stringWithFormat:@"%@/%.0fML",self.progress,self.total];
        
        
        // 取出当前时间
        NSDate * date = [NSDate date];
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"HH:mm";
        NSString * time = [formatter stringFromDate:date];
        
        // 保存数据'
        NSString * sql =   [NSString stringWithFormat:@"UPDATE t_mainSeting SET progress='%@',lastTime='%@';",self.progress,time];
        
        BOOL success         =  [self.database executeUpdate:sql];
        
        if (success) {
            //NSLog(@"数据更新成功");
        } else {
            //NSLog(@"数据更新失败");
        }

        self.lastTime = time;
        self.bottomTip.text = [NSString stringWithFormat:@"上一次喝水的时间是:%@",self.lastTime];
        formatter.dateFormat = @"MM:dd";
        
        NSString *timeStr = [formatter stringFromDate:date];
        // 加入一条详细时间,方便详细记录使用
        formatter.dateFormat = @"yyyy:MM:dd";
        NSString * fullTime  = [formatter stringFromDate:date];
        // 先查找 如果没有今天的记录就先增加一条   如果有就更新
        NSString * sql3_1 = [NSString stringWithFormat:@"SELECT time FROM t_record WHERE time = '%@';",timeStr];
        
        FMResultSet * result = [self.database executeQuery:sql3_1];
        
        if ([result next]) {
            // 已存在
            NSString * sql3_2 =   [NSString stringWithFormat:@"UPDATE t_record SET time='%@',volume='%@',total='%d',fullTime='%@' WHERE time = '%@';",timeStr,self.progress,(int)self.total,fullTime,timeStr];
            BOOL success3         =  [self.database executeUpdate:sql3_2];
        } else {
            // 不存在  插入一条
            NSString * sql3_3 =   [NSString stringWithFormat:@"INSERT INTO t_record(time,volume,total,fullTime) VALUES('%@','%d','%d','%@')",timeStr,self.progress.intValue,(int)self.total,fullTime];
            
            BOOL success3         =  [self.database executeUpdate:sql3_3];
        }
    }
}
#pragma mark   喝水进度的懒加载 及控制喝水按钮的状态

- (void)setProgress:(NSString *)progress {

    _progress = progress;
    
    if (progress.intValue >= self.total) {
        self.startBtn.enabled = NO;
        self.doneView.hidden  = NO;
        NSString * sql = @"UPDATE t_mainSeting SET setButtonState = 2;";
        BOOL success         =  [self.database executeUpdate:sql];
    }
 
}
#pragma mark  封装查询过程
- (void)selectWithState:(BOOL)success {
    if (success) {
        NSString *sql       = @"SELECT  setButtonState,progress,lastTime FROM t_mainSeting ;";
        FMResultSet *result = [self.database executeQuery:sql];
        while ([result next]) {

            self.setButtonState       =   [result intForColumnIndex:0];
            _progress             =   [result stringForColumnIndex:1];
            self.lastTime             =   [result stringForColumnIndex:2];
        }
        
        // 查询体重
        NSString *sql1       = @"SELECT weightStr  FROM t_firstSeting;";
        FMResultSet *result1 = [self.database executeQuery:sql1];
        while ([result1 next]) {
            self.weightStr       =   [result1 stringForColumnIndex:0];
            NSLog(@"%@--------",self.weightStr);
        }
    }
}

- (BOOL)prefersStatusBarHidden {

    return YES;
}

@end
